#!/usr/bin/env node

/**
 * 初始化停车场分类数据脚本
 * 
 * 使用方法：
 * node scripts/init_categories.js
 */

const { query, testConnection } = require('../config/db');

async function initCategories() {
  try {
    console.log('🔄 正在连接数据库...');
    
    // 测试数据库连接
    const isConnected = await testConnection();
    if (!isConnected) {
      console.error('❌ 数据库连接失败，请检查配置');
      process.exit(1);
    }

    console.log('🔄 正在检查现有分类数据...');
    
    // 检查是否已有分类数据
    const existingCategories = await query('SELECT COUNT(*) as count FROM parking_lot_categories');
    
    if (existingCategories[0].count > 0) {
      console.log('ℹ️  分类数据已存在，跳过初始化');
      process.exit(0);
    }

    console.log('🔄 正在插入初始分类数据...');
    
    // 初始分类数据
    const categories = [
      { name: '商业中心', icon_url: '', sort_order: 1 },
      { name: '住宅小区', icon_url: '', sort_order: 2 },
      { name: '医院', icon_url: '', sort_order: 3 },
      { name: '学校', icon_url: '', sort_order: 4 },
      { name: '办公楼', icon_url: '', sort_order: 5 },
      { name: '酒店', icon_url: '', sort_order: 6 },
      { name: '景区', icon_url: '', sort_order: 7 },
      { name: '交通枢纽', icon_url: '', sort_order: 8 },
      { name: '其他', icon_url: '', sort_order: 9 }
    ];

    // 批量插入分类数据
    const insertQuery = `
      INSERT INTO parking_lot_categories (name, icon_url, sort_order) 
      VALUES (?, ?, ?)
    `;

    for (const category of categories) {
      await query(insertQuery, [category.name, category.icon_url, category.sort_order]);
    }

    console.log('✅ 停车场分类数据初始化成功！');
    console.log(`📊 共插入 ${categories.length} 个分类`);
    
    // 显示插入的分类
    const insertedCategories = await query('SELECT * FROM parking_lot_categories ORDER BY sort_order');
    console.log('\n📋 已创建的分类：');
    insertedCategories.forEach(cat => {
      console.log(`   ${cat.id}. ${cat.name} (排序: ${cat.sort_order})`);
    });

  } catch (error) {
    console.error('❌ 初始化过程中发生错误:', error.message);
    process.exit(1);
  } finally {
    process.exit(0);
  }
}

// 执行初始化
initCategories();
